package com.portal.common.redis.aspect;


import com.portal.common.core.exception.ServiceException;
import com.portal.common.core.utils.StringUtils;
import com.portal.common.core.utils.ip.IpUtils;
import com.portal.common.redis.anno.LimitType;
import com.portal.common.redis.anno.RateLimiter;
import com.portal.common.redis.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;

@Slf4j
@Aspect
@Component
public class RateLimiterAspect {
    @Resource
    private RedisService redisService;
    // 限流处理
    @Before("@annotation(rateLimiter)")
    public void doBefore(JoinPoint point, RateLimiter rateLimiter){
        // 获取注解的限流时间
        int time = rateLimiter.time();
        // 获取注解的限流数量
        int count = rateLimiter.count();
        // 生成键
        String combineKey = getCombineKey(rateLimiter, point);
        // 将键存入列表
        List<Object> keys = Collections.singletonList(combineKey);
        try
        {
            Long number = redisService.execute("limitScript", keys, count, time);
            if (StringUtils.isNull(number) || number.intValue() > count)
            {
                throw new ServiceException("访问过于频繁，请稍候再试");
            }
            log.info("限制请求'{}',当前请求'{}',缓存key'{}'", count, number.intValue(), combineKey);
        }
        catch (ServiceException e)
        {
            throw e;
        }
        catch (Exception e)
        {
            throw new RuntimeException("服务器限流异常，请稍候再试");
        }
    }
    public String getCombineKey(RateLimiter rateLimiter, JoinPoint point) {
        // 初始化限流键基础部分
        StringBuffer stringBuffer = new StringBuffer(rateLimiter.key());

        // 如果限流类型为 IP，则追加 IP 地址
        if (rateLimiter.limitType() == LimitType.IP) {
            stringBuffer.append(IpUtils.getIpAddr()).append("-");
        }

        // 获取方法签名
        MethodSignature signature = (MethodSignature) point.getSignature();

        // 获取方法对象
        Method method = signature.getMethod();

        // 获取方法所在类
        Class<?> targetClass = method.getDeclaringClass();

        // 拼接类名和方法名
        stringBuffer.append(targetClass.getName()).append("-").append(method.getName());

        // 返回组合后的限流键
        return stringBuffer.toString();
    }
}
